#ifndef BENCODE_H
#define BENCODE_H

/**
 * Bencode is an encoding widely used in <a href="http://www.bittorrent.org/protocol.html">BitTorrent</a>
 * for structured data, especially in .torrent files and tracker responses.
 * A group of API are provided for parsing bencoded data.
 * @file  bencode.h
 * @brief Bencode Parser and Dumper
 */

#include "alp_type.h"
#include "alp_list.h"
#include "alp_dict.h"

/** Abstract type for bencode nodes. */
typedef struct bencode_node_t
{
	enum {BENCODE_STRING = 0, BENCODE_INT, BENCODE_LIST, BENCODE_DICT} type;
	union
	{
		struct
		{
			const char *buffer;
			size_t length;
		};
		alp_list_t *list;
		alp_dict_t *dict;
	};
}bencode_node_t;

/**
 * Parse a bencoded buffer.
 * @param node the bencode node to be created
 * @param buf  the buffer
 * @param len  on entry, the length of the buffer; on exit, the length of the buffer left
 * @param pool the pool to allocate the node out of
 */
alp_status_t bencode_parse(bencode_node_t **node, const char *buf, size_t *len);

/**
 * Dump a bencode node.
 * @param node     the bencode node to be dumped
 * @param userdata the user data for the callback
 * @param callback the callback function for dumping data
 */
alp_status_t bencode_dump(bencode_node_t *node, void *userdata, alp_status_t (*callback)(void *userdata, const char *buf, size_t len));

alp_status_t alp_bencode_destroy(bencode_node_t *node);

#endif
